package com.centling.smartSealForPhone.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.media.ExifInterface;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.ImageUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.PhoneNumCheck;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.view.RoundImgView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PersonCenterFragment extends TitleBarFragment {

    private RoundImgView avatar;
    private TextView username;
    private TextView username2;
    private TextView realname;
    private TextView phone;
    private TextView edit;
    private EditText phone_edit;
    private TextView department;
    private EditText department_edit;

    private boolean isEdit = false;

    private AlertDialog dialog;

    private String filePath = Environment.getExternalStorageDirectory().getPath() + "/temp.jpg";
    private Uri imageUri;

    public static PersonCenterFragment getInstance() {
        PersonCenterFragment fragment = new PersonCenterFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int setLayoutResource() {
        return R.layout.fragment_person_center;
    }

    @Override
    public void findViewInThisFunction(View rootView) {
        setTitleBarText("个人中心");
        setTitleBarVisibility(View.GONE);
        initView(rootView);

        setData();
    }

    public void initView(View view) {
        avatar = view.findViewById(R.id.person_avatar);
        username = view.findViewById(R.id.person_username);
        username2 = view.findViewById(R.id.person_username2);
        realname = view.findViewById(R.id.person_realname);
        phone = view.findViewById(R.id.person_phone);
        edit = view.findViewById(R.id.person_edit);
        phone_edit = view.findViewById(R.id.person_phone_edit);
        department = view.findViewById(R.id.person_department);
        department_edit = view.findViewById(R.id.person_department_edit);

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isEdit) {
                    uploadInfo();
                } else {
                    isEdit = true;
                    phone.setVisibility(View.GONE);
                    phone_edit.setVisibility(View.VISIBLE);
                    department.setVisibility(View.GONE);
                    department_edit.setVisibility(View.VISIBLE);
                    edit.setText("确定");
                }
            }
        });
        avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    if (dialog == null) {
                        dialog = new AlertDialog.Builder(getActivity()).setItems(new String[]{"相机", "相册"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                    startActivityForResult(intent2, 1);
                                } else {
                                    Intent intent = new Intent();
                                    intent.setAction(Intent.ACTION_PICK);
                                    intent.setType("image/*");
                                    startActivityForResult(intent, 0);
                                }
                            }
                        }).create();
                    }
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                }
//            }
        });
    }

    public void setData() {
        ImageUtil.loadAvatarImage(SPUtil.getString(SPConstants.AVATAR), avatar, R.drawable.iv_avatar_default);

        File tempFile = new File(filePath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", tempFile);
        } else {
            imageUri = Uri.fromFile(tempFile);
        }
        username.setText(SPUtil.getString(SPConstants.USER_NAME));
        username2.setText(SPUtil.getString(SPConstants.USER_NAME));
        realname.setText(SPUtil.getString(SPConstants.REAL_NAME));
        phone.setText(SPUtil.getString(SPConstants.PHONE));
        phone_edit.setText(SPUtil.getString(SPConstants.PHONE));
        department.setText(SPUtil.getString(SPConstants.DEPARTMENT));
        department_edit.setText(SPUtil.getString(SPConstants.DEPARTMENT));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        try {
            if (resultCode != Activity.RESULT_CANCELED) {
                switch (requestCode) {
                    case 0:
                        startPhotoZoom(intent.getData());
                        break;
                    case 1:
                        startPhotoZoom(null);
                        break;
                    case 2:
                        final Bitmap bitmap = BitmapFactory.decodeFile(filePath);

                        ByteArrayOutputStream myStream = new ByteArrayOutputStream();
                        String bitmapData = "";
                        if (bitmap != null) {
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, myStream);
                            byte[] myCopyByte = myStream.toByteArray();
                            int myLength = myCopyByte.length;
                            bitmapData = Base64.encodeToString(myCopyByte, 0, myLength, Base64.DEFAULT);
                        }
                        Map<String, String> param = new HashMap<>();
                        param.put("userId", SPUtil.getString(SPConstants.USER_ID));
                        param.put("avatar", bitmapData);
                        mProcessDialog.setTitle("正在修改头像").showNormal();
                        putJsonEnqueue(UrlConstants.EDIT_USER_AVATAR, param, new OkHttpUtil.NetCallBack() {
                            @Override
                            public void onSucceed(String json) {
                                JSONObject data = null;
                                try {
                                    data = new JSONObject(json);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                mProcessDialog.dismiss();
                                ShowToast.shortTime("修改成功");
                                ImageUtil.loadAvatarImage(data.optString("avatar"), avatar, R.drawable.iv_avatar_default);
                                SPUtil.setString(SPConstants.AVATAR, data.optString("avatar"));
                            }

                            @Override
                            public void onFailed(String reason) {
                                mProcessDialog.dismiss();
                                ShowToast.shortTime(reason);

                            }
                        });
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            //Toast.makeText(this, "获取图片失败", 0).show();
            e.printStackTrace();
        }
    }

    public void startPhotoZoom(Uri uri) {
        if (uri == null) {
            int degree = readPictureDegree(filePath);
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 2;
            Bitmap originBitmap = BitmapFactory.decodeFile(filePath, opts);
            uri = Uri.parse(MediaStore.Images.Media.insertImage(mActivity.getContentResolver(),
                    rotatingImageView(originBitmap, degree), null, null));
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filePath)));
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("return-data", false);
        startActivityForResult(intent, 2);
    }

    private int readPictureDegree(String picturePath) {
        try {
            ExifInterface exifInterface = new ExifInterface(picturePath);
            int type = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (type) {
                case ExifInterface.ORIENTATION_NORMAL:
                    return 0;
                case ExifInterface.ORIENTATION_ROTATE_90:
                    return 90;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    return 180;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    return 270;
                default:
                    return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    private Bitmap rotatingImageView(Bitmap bitmap, int angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                true);
    }

    public void uploadInfo() {
        final String phoneNum = phone_edit.getText().toString().trim();
        final String departmentName = department_edit.getText().toString().trim();

        if (!TextUtils.isEmpty(phoneNum)&&!PhoneNumCheck.isMobileNo(phoneNum)) {
            ShowToast.shortTime("请输入正确的手机号");
            return;
        }
//        if (TextUtils.isEmpty(departmentName)) {
//            ShowToast.shortTime("请输入部门");
//            return;
//        }
//        if (departmentName.length() > 50) {
//            ShowToast.shortTime("部门名称不能超过50");
//            return;
//        }

        String id = SPUtil.getString(SPConstants.USER_ID);

        Map<String, String> param = new HashMap<>();
        param.put("userId", id);
        param.put("phone", phoneNum);
        param.put("department", departmentName);
        param.put("userName", "");
        param.put("realName", "");
        param.put("avatar", "");
        putJsonEnqueue(UrlConstants.EDIT_USERINFO, param, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                ShowToast.shortTime("修改个人信息成功");
                isEdit = false;
                edit.setText("编辑");
                phone_edit.setVisibility(View.GONE);
                phone.setVisibility(View.VISIBLE);
                phone.setText(phoneNum);
                department.setVisibility(View.VISIBLE);
                department.setText(departmentName);
                department_edit.setVisibility(View.GONE);
                try {
                    JSONObject data = new JSONObject(json);
                    SPUtil.setString(SPConstants.PHONE, data.optString("phone"));
                    SPUtil.setString(SPConstants.DEPARTMENT, data.optString("department"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String reason) {
                ShowToast.shortTime("修改失败");
            }
        });
    }
}

